﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AnalisisDeRiesgos.Dal;
using System.Web.Mvc;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace AnalisisDeRiesgos.Models.Action
{
    public class RegisterActionModel
    {
        public int DangerId { get; set; }

        [DisplayName("Nombre de la Actividad *")]
        [Required(ErrorMessage = "El tipo de actividad es necesario")]        
        public int Type { get; set; }

        [DisplayName("Accion *")]
        [Required(ErrorMessage = "La accion es requerida")]
        [StringLength(100, ErrorMessage = "Toda la accion debe tener como maximo 100 caracteres")]        
        public string DescriptionAction { get; set; }

        [DisplayName("Responsable")]      
        public int Responsible { get; set; }

        [DisplayName("Fecha programada")]                        
        public string ProgrammedDate { get; set; }

        [DisplayName("Fecha de ejecucion")]        
        public string ExecutionDate { get; set; }

        [DisplayName("Estado (%)")]        
        [StringLength(3, ErrorMessage = "El estado solo puede ser 3 cifras")]
        [RegularExpression(@"^[0-9.,]+$", ErrorMessage = "El estado solo puede ser un numero")]
        public string Status { get; set; }

        public IEnumerable<SelectListItem> ActionTypes
        {
            get
            {
                return actionList;
            }
        }

        private List<SelectListItem> actionList;

        riskanalysisEntities entities = new riskanalysisEntities();

        public RegisterActionModel() : this(0)
        {}

        public RegisterActionModel(int dangerId)
        {
            DangerId = dangerId;
            Type = 1;
            DescriptionAction = "";
            Responsible = (from u in entities.users
                           where u.enabled && u.privilege == 1
                           select u).FirstOrDefault().CI;
            ProgrammedDate = DateTime.Today.ToString("d", Utils.culture);
            ExecutionDate = "1/1/2000";
            Status = "0";
            FillList();
        }

        private void FillList()
        {
            actionList = Utils.FillAvailableActionTypesList(DangerId);
        }

        public void Save()
        {
            entities.AddToactions(
                new action
                {
                    type = Type,
                    dangerId = DangerId,
                    description = DescriptionAction,
                    executionDate = Convert.ToDateTime(ExecutionDate, Utils.culture),
                    programedDate = Convert.ToDateTime(ProgrammedDate, Utils.culture),
                    responsible = Responsible,
                    status = Convert.ToInt32(Status)
                });
            entities.SaveChanges();
        }
    }
}